//
//  KBPictureView.swift
//  KimboWeiBoSwift
//
//  Created by kimbo on 15/12/21.
//  Copyright © 2015年 kimbo. All rights reserved.
//

import UIKit
import SDWebImage

class KBPictureView: UICollectionView {
    
    // MARK: - 属性
    var status: KBStatus? {
        didSet {
            self.reloadData()//防止重用
        }
    }
    
    private let reuseIdentifier = "KBCollectionViewCell"
    
    private let layout = UICollectionViewFlowLayout()
    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        //注册cell
        registerClass(KBCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        self.dataSource = self
        
        backgroundColor = UIColor.clearColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    /// 返回对应配图的尺寸
    func calcItemSize() -> CGSize {
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        //设置layout参数
        layout.itemSize = itemSize
        
        let count = status?.pictureURLs?.count ?? 0
        
        //没有图片
        if count == 0 {
            return CGSizeZero
        }
        
        //一张图片
        if count == 1 {
            var oneItemSize = CGSize(width: 150, height: 120)
            
            let url = status?.pictureURLs![0]
            // 从本地预缓存中取得图片
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url?.absoluteString) {
                
                oneItemSize = image.size
                
                if oneItemSize.width < 40 { //如果图片过小
                    oneItemSize.width = 40
                } else if oneItemSize.width > UIScreen.mainScreen().bounds.width * 0.5 {
                    //如果图片过大
                    oneItemSize.width = UIScreen.mainScreen().bounds.width * 0.5
                }
            }
            
            layout.itemSize = oneItemSize
            return oneItemSize
        }
        
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
        //4张图片
        if count == 4 {
            let widthOrHeight =  2 * itemSize.width + margin
            let fourItemSize = CGSize(width: widthOrHeight, height: widthOrHeight)
            return fourItemSize
        }
        
        // 其他情况(其他张数)
        // 列数,行数计算依赖列数,column必须为Int
        let column = 3
        // 宽度 = 列数 * cell的宽度 + (列数 - 1) * 间距
        let width = CGFloat(column) * itemSize.width + (CGFloat(column) - 1) * margin
        // 行数 = (图片的数量(Int) + 列数(Int) - 1) / 列数(Int)
        let row = (count + column - 1) / column
        // 高度 = 行数 * cell的高度 + (行数 - 1) * 间距
        let height = CGFloat(row) * itemSize.height + (CGFloat(row) - 1) * margin
        
        return CGSize(width: width, height: height)
    }
}


// MARK: - UICollectionView数据源和代理方法
extension KBPictureView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! KBCollectionViewCell
        
        cell.imageURL = status?.pictureURLs![indexPath.item]
        
        return cell
    }
}



// MARK: - 自定义UICollectionViewCell
class KBCollectionViewCell: UICollectionViewCell {
    
    // MARK: - 属性
    private var imageURL: NSURL? {
        didSet {
            imageView.sd_setImageWithURL(imageURL)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(imageView)
        
        imageView.ff_Fill(contentView)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载
    private lazy var imageView: UIImageView = {
       let imageView = UIImageView()
        
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        
        imageView.clipsToBounds = true
        
        return imageView
    }()
}


